package gemini.castor.ui.client.page.menu;

import gemini.castor.ui.client.utils.PlaceConstants;
import gemini.castor.ui.client.utils.PlaceConstants.MenuItem;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.HasHandlers;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;


public class MenuWidget extends Composite implements HasHandlers{
		
	private HorizontalPanel pnlContainer;
	
	private HTML currentMenu;
	private HTML currentMenuMove;
	private MenuItem currentItem = MenuItem.HOME;

	private MenuWidgetConstants constants;

	public MenuWidget(){
		constants = GWT.create(MenuWidgetConstants.class);
		initCustom();
		initWidget(pnlContainer);
	}
	
	private void initCustom(){
		pnlContainer = new HorizontalPanel();
		pnlContainer.addStyleName("pnlMenuContainer");
		for (MenuItem mnuItem : PlaceConstants.MenuItem.values()) {
			pnlContainer.add(createMnuHtml(mnuItem));
		}
	}
	
	private HTML createMnuHtml(final MenuItem mnuItem){
		HTML htm = new HTML(constants.getString(mnuItem.getTextKey()));
		htm.setStylePrimaryName("htmMenu");
		htm.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				if(currentMenu != null){
					currentMenu.removeStyleDependentName("down");
				}
				currentMenu = (HTML)event.getSource();
				currentMenu.addStyleDependentName("down");
				currentItem = mnuItem;
				fireEvent(new MenuEvent(mnuItem));
			}
		});
		htm.addMouseOverHandler(new MouseOverHandler() {

			@Override
			public void onMouseOver(MouseOverEvent event) {
				if (currentMenuMove != null) {
					currentMenuMove.removeStyleDependentName("hover");
				}
				currentMenuMove = (HTML) event.getSource();
				if (currentMenuMove != currentMenu) {
					currentMenuMove.addStyleDependentName("hover");
				}
			}
		});
		htm.addMouseOutHandler(new MouseOutHandler() {

			@Override
			public void onMouseOut(MouseOutEvent event) {
				if (currentMenuMove != null) {
					currentMenuMove.removeStyleDependentName("hover");
				}
			}
		});
		
		if(mnuItem.equals(MenuItem.HOME)){
			htm.addStyleDependentName("down");
			currentMenu = htm;
		}
		
		
		return htm;
	}
	
	public void fireCurrentButtonEvent(){
		fireEvent(new MenuEvent(currentItem));
	}
	
	public HandlerRegistration addSelectedHandler( MenuHandler handler) {
		return addHandler(handler,  MenuEvent.getType());
	}
}
